package com.cmwa.scbp.sys.permission.operRole.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmwa.scbp.sys.menu.entity.MenuVo;
import com.cmwa.scbp.sys.menu.entity.TreeElem;
import com.cmwa.scbp.sys.menu.service.MenuService;
import com.cmwa.scbp.sys.permission.operRole.entity.OperRoleVo;
import com.cmwa.scbp.sys.permission.operRole.service.OperRoleManageService;
import com.cmwa.scbp.utils.NumberComparator;

import net.sf.json.JSONArray;

@Controller
@RequestMapping(value = "/sys/oper/roleAuth")
public class OperRoleManageController {
	
	private final String ROLE_PREFIX = "R-";
	/**
	 * 设置jsp的访问路径
	 */
	private final static String PAGE_PATH = "system/sys/permission/operRole/"; 
	@Resource
	private OperRoleManageService roleManageService;
	@Resource
	private MenuService menuService;
	
	/**
	 * 角色菜单权限管理页面
	 * 
	 * @param orgId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/operRoleManageView")
	public String menuAuthManageView(Model model) throws IOException {
		List<OperRoleVo> roles = roleManageService.roleList();
		model.addAttribute("roles", roles);
		return PAGE_PATH + "operRoleManage";
	}
	
	/**
	 * ajax 根据角色ID查询人员列表
	 * @param roleId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/ajaxRoleList")
	public void ajaxRoleList(@RequestParam(value="roleId",required=false) String roleId, HttpServletResponse response) throws IOException {
		List<TreeElem> elems = new ArrayList<TreeElem>();

		if (roleId == null || "".equals(roleId)) {
			//获取角色
			List<OperRoleVo> roles = roleManageService.roleList();
			for (OperRoleVo vo : roles) {
				TreeElem elem = new TreeElem();
				elem.getState().setLoaded(true).setOpened(true);
				elem.setId(ROLE_PREFIX+vo.getRoleId());
				elem.setText(vo.getRoleName());
				elems.add(elem);
			}
		}

		PrintWriter out = response.getWriter();
		response.setContentType("application/json;charset=UTF-8");
		out.write(JSONArray.fromObject(elems).toString());
	}
	
	/**
	 * 查询某个角色的权限菜单
	 * 
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/ajaxMenuList")
	public void ajaxMenuList(@RequestParam("roleId") String roleId,
			@RequestParam("belongSystem") String belongSystem,
			HttpServletResponse response) throws Exception {
		// 查询默认选中的菜单
		List<String> selectedMenu = null;
		selectedMenu = roleManageService.queryRoleDefaultSelectedMenu(roleId);
	
		// 查询三级的菜单树
		List<MenuVo> list = menuService.queryThreeLevelMenuList(belongSystem);
		sortTheMenu(list);
		List<TreeElem> elems = new ArrayList<TreeElem>();
		// 构建一棵带有默认选中的菜单树
		for (MenuVo vo : list) {
			TreeElem elem = new TreeElem();
			elem.getState().setLoaded(true).setOpened(true);
			setDefaultSelected(selectedMenu, vo, elem);
			elem.setId(vo.getMenuId());
			elem.setText(vo.getName());
			if (vo.getChilds() != null) {
				sortTheMenu(vo.getChilds());
				// 二级菜单
				for (MenuVo second : vo.getChilds()) {
					TreeElem secElem = new TreeElem();
					secElem.getState().setLoaded(true).setOpened(true);
					setDefaultSelected(selectedMenu, second, secElem);
					secElem.setId(second.getMenuId());
					secElem.setText(second.getName());
					elem.getChildren().add(secElem);
					// 三级菜单
					if (second.getChilds() != null) {
						sortTheMenu(second.getChilds());
						for (MenuVo third : second.getChilds()) {
							TreeElem thirdElem = new TreeElem();
							thirdElem.getState().setLoaded(true).setOpened(true);
							setDefaultSelected(selectedMenu, third, thirdElem);
							thirdElem.setId(third.getMenuId());
							thirdElem.setText(third.getName());
							secElem.getChildren().add(thirdElem);
						}
					}
				}
			}
			elems.add(elem);
		}
		PrintWriter out = response.getWriter();
		response.setContentType("application/json;charset=UTF-8");
		out.write(JSONArray.fromObject(elems).toString());
	}
	
	/**
	 * 展示按钮菜单列表数据
	 * 
	 * @param authId
	 * @param menuIds
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/ajaxDisplayButtonMenu")
	public void ajaxDisplayButtonMenu(@RequestParam("roleId") String roleId, 
			  @RequestParam("menuIds") String menuIds,
			  @RequestParam("belongSystem") String belongSystem,
			  @RequestParam(value = "mType", required = false) String mType,
			  HttpServletResponse response) throws Exception {
		try {
			// 获取所有按钮菜单
			List<MenuVo> allMenuVos = menuService.queryAllButtonMenuByMenuIds(menuIds, mType, belongSystem);
			// 被选中的按钮菜单
			List<MenuVo> selectedMenuVos = roleManageService.queryRoleDefaultSelectedButtonMenu(roleId, mType, belongSystem);
			Set<String> selectedButton = asSet(selectedMenuVos);
			List<TreeElem> elems = new ArrayList<TreeElem>();
			// 构建一棵带有默认选中的菜单树
			for (MenuVo vo : allMenuVos) {
				TreeElem elem = new TreeElem();
				elem.getState().setLoaded(true).setOpened(true);
				setDefaultSelected(selectedButton, vo, elem);
				elem.setId(vo.getMenuId());
				elem.setText(vo.getName());
				if (vo.getChilds() != null) {
					sortTheMenu(vo.getChilds());
					// 二级菜单
					for (MenuVo second : vo.getChilds()) {
						TreeElem secElem = new TreeElem();
						secElem.getState().setLoaded(true).setOpened(true);
						setDefaultSelected(selectedButton, second, secElem);
						secElem.setId(second.getMenuId());
						secElem.setText(second.getName()+"("+second.getDesc()+")");
						elem.getChildren().add(secElem);

					}
				}
				elems.add(elem);
			}

			PrintWriter out = response.getWriter();
			response.setContentType("application/json;charset=UTF-8");
			out.write(JSONArray.fromObject(elems).toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存按钮进行保存选中的菜单
	 * 
	 * @param roleId
	 * @param menuIds
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/ajaxSaveRoleAuth")
	@ResponseBody
	public String ajaxSaveRoleAuth(@RequestParam("roleId") String roleId,
			@RequestParam("belongSystem") String belongSystem,
			@RequestParam("menuIds") String menuIds) throws Exception {
		roleManageService.saveRoleMenu(roleId, menuIds, belongSystem);
		return "success";
	}
	
	/**
	 * 复制一个角色权限菜单给另一个角色
	 * 
	 * @param empId
	 * @param stId
	 * @param response
	 * @param merge  是否粘贴覆盖权限菜单
	 * @throws Exception
	 */
	@RequestMapping("/copyOrmemberMenuToNext")
	@ResponseBody
	public String copyOrmemberMenuToNext(@RequestParam("srcId") String srcId,
			@RequestParam("belongSystem") String belongSystem,
			@RequestParam("destId") String destId,
			@RequestParam("merge") Boolean merge) throws Exception {
		String roleMenu = roleManageService.queryRoleDefaultSelectedMenuWithComma(srcId/*checkResolving(srcId)*/,destId/*checkResolving(destId)*/,merge);
		roleManageService.saveRoleMenu(destId, roleMenu,belongSystem);
		return "success";
	}
	
	/**
	 * 清空权限菜单
	 * 
	 * @param empId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/clearMenu")
	@ResponseBody
	public String clearMenu(@RequestParam("roleId") String roleId,
			@RequestParam("belongSystem") String belongSystem) throws Exception {
		roleManageService.saveRoleMenu(roleId, "",belongSystem);
		return "success";
	}
	
	/**
	 * 设置默认选中
	 * 
	 * @param selectedMenu
	 * @param menuVo
	 * @param elem
	 */
	private void setDefaultSelected(Set<String> selectedMenu, MenuVo menuVo, TreeElem elem) {
		// 不是叶子节点，不设置为选中状态
		if (selectedMenu.contains(menuVo.getMenuId()) && menuVo.getChilds().size() == 0) {
			elem.getState().setSelected(true);
		}
	}
	
	/**
	 * 设置默认选中
	 * 
	 * @param selectedMenu
	 * @param menuVo
	 * @param elem
	 */
	private void setDefaultSelected(List<String> selectedMenu, MenuVo menuVo, TreeElem elem) {
		// 不是叶子节点，不设置为选中状态
		if (selectedMenu.contains(menuVo.getMenuId()) && menuVo.getChilds().size() == 0) {
			elem.getState().setSelected(true);
		}
	}
	
	/**
	 * 根据sequence排序菜单
	 * 
	 * @param list
	 */
	private void sortTheMenu(List<MenuVo> list) {
		Collections.sort(list, new NumberComparator());
	}

	private Set<String> asSet(List<MenuVo> list) {
		Set<String> set = new HashSet<String>();
		if (list != null) {
			for (MenuVo m : list) {
				set.add(m.getMenuId());
			}
		}
		return set;
	}

}
